<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow>
      <!-- 头部功能 -->
      <template #header>
        <div>
          <el-input
            clearable
            placeholder="请输入查询关键字"
            v-model="query"
            class="input-with-select"
            style="width: 400px"
            @clear="reloadUserlistQuery"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              style="width: 50px"
              @click="reloadUserlistQuery"
            ></el-button>
          </el-input>

          <el-button
            type="primary"
            @click="showAddUserPage()"
            class="addUser"
            >添加新用户</el-button
          >
          <el-dialog title="添加新用户" :visible.sync="addFormVisible">
            <el-form :model="user" ref="addUserForm" :rules="$rules.user">
              <el-form-item
                prop="username"
                label="用户名"
                :label-width="formLabelWidth"
              >
                <el-input v-model="user.username"> </el-input>
              </el-form-item>
              <el-form-item
                prop="password"
                label="密码"
                :label-width="formLabelWidth"
              >
                <el-input v-model="user.password" show-password> </el-input>
              </el-form-item>
              <el-form-item
                prop="email"
                label="邮箱"
                :label-width="formLabelWidth"
              >
                <el-input v-model="user.email"> </el-input>
              </el-form-item>
              <el-form-item
                prop="mobile"
                label="电话"
                :label-width="formLabelWidth"
              >
                <el-input v-model.number="user.mobile"> </el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="addFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUserList()">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </template>

      <!-- 正文内容 -->
      <el-table border :data="users" v-loading="loading">
        <el-table-column prop="id" label="序号" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 状态的v-model绑定运用的引用数据类型完成双向绑定 -->
        <el-table-column label="状态" #default="{ row }"
          ><el-switch
            v-model="row.mg_state"
            @change="updateUserSate(row)"
          ></el-switch>
        </el-table-column>
        <el-table-column label="操作" width="200" #default="{ row }">
          <el-tooltip
            class="item"
            effect="dark"
            content="用户编辑"
            placement="bottom"
          >
            <el-button
              class="updateUser"
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updateUserData(row)"
            ></el-button>
          </el-tooltip>
          <el-dialog title="修改用户" :visible.sync="updateFormVisible">
            <el-form :model="user" ref="updateUserForm" :rules="$rules.user">
              <el-form-item
                prop="username"
                label="用户名"
                :label-width="formLabelWidth"
              >
                <el-input v-model="user.username" disabled> </el-input>
              </el-form-item>
              <el-form-item
                prop="email"
                label="邮箱"
                :label-width="formLabelWidth"
              >
                <el-input v-model="user.email"> </el-input>
              </el-form-item>
              <el-form-item
                prop="mobile"
                label="电话"
                :label-width="formLabelWidth"
              >
                <el-input v-model.number="user.mobile"> </el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="updateFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="modifyUserById()"
                >确 定</el-button
              >
            </div>
          </el-dialog>

          <!-- 
          <template>
            <el-popconfirm title="这是一段内容确定删除吗？">
            <el-button slot="reference">删除</el-button>
          </el-popconfirm>
          </template> -->

          <el-tooltip
            class="item"
            effect="dark"
            content="删除用户"
            placement="bottom"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(row.id)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="分配权限"
            placement="bottom"
          >
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              size="mini"
              @click="allotLimit(row)"
            ></el-button>
          </el-tooltip>
          <el-dialog
            title="角色分配"
            :visible.sync="limitFormVisible"
            width="400px"
          >
            <el-form
              :model="userlimit"
              ref="limitRoleForm"
              :rules="$rules.role"
            >
              <el-form-item
                prop="username"
                label="当前用户"
                :label-width="formLabelWidth"
              >
                <el-input v-model="userlimit.username" disabled> </el-input>
              </el-form-item>
              <el-form-item
                prop="role_name"
                label="当前权限"
                :label-width="formLabelWidth"
              >
                <el-input v-model="userlimit.role_name"> </el-input>
              </el-form-item>
              <el-form-item
                prop="role_new_name"
                label="新权限"
                :label-width="formLabelWidth"
              >
                <el-select
                  v-model="userlimit.role_new_name"
                  placeholder="选择新权限"
                  @change="setRoleNewName($event)"
                >
                  <el-option
                    v-for="item in roles"
                    :key="item.id"
                    :label="item.roleName"
                    :value="`${item.id}+${item.roleName}`"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="limitFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateLimitData(row)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="reloadUserlistSize"
        @current-change="reloadUserlistPage"
        :current-page="pagenum"
      >
      </el-pagination>
      <!-- @size-change="handleSizeChange" pageSize改变时触发(每一页)
        @current-change="handleCurrentChange" currentPage 改变时触发(当前页)
        :current-page="currentPage" 当前页数-->
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      users: [],
      total: 16, //总页数
      pagesize: 5, //页面数据调
      pagenum: 1, //当前页码
      query: "", //加载页面条件限制参数
      loading: false,
      user: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      userlimit: {
        username: "",
        role_name: "",
        role_new_name: "",
      },
      roles: {},
      newRoleName: "",
      rid: 0,
      addFormVisible: false,
      updateFormVisible: false,
      limitFormVisible: false,
      formLabelWidth: "100px",
      id: "",
    };
  },
  methods: {
    setRoleNewName(newStr) {
      // console.log(1111,newStr);
      let rid = newStr.split("+")[0];
      let newName = newStr.split("+")[1];
      this.newRoleName = newName;
      this.rid = rid;

      // console.log(1232,this.newRoleName,this.rid);
    },
    //初始化数据
    async initUserList() {
      try {
        this.loading = true;
        let users = await this.$api.getUserList({
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        });
        if (users == "error") return;
        this.users = users.users;
        this.total = users.total;
        this.pagenum = users.pagenum; // 这行代码可以定义也可以不定义，主要为保证和后端服务器结果同步
        // console.log(1111111111, users);
      } catch (error) {
        console.log("UserView-loadUserListPage-error:", error);
      } finally {
        this.loading = false;
      }
    },
    //更新查询user的参数
    reloadUserlistQuery() {
      this.pagenum = 1;
      this.initUserList();
    },

    //添加页面的展示和页面的清空
    showAddUserPage() {
      this.initUserList();
      this.user = {
        username: "",
        password: "",
        email: "",
        mobile: "",
      };
      this.addFormVisible = true;
    },
    //添加新用户
    async addUserList() {
      try {
        this.addFormVisible = false;
        // console.log(this.$refs.addUserForm);
        await this.$refs.addUserForm.validate(); //对$refs里的addUserForm(该表单的输入值)进行校验
        let data = await this.$api.addUserList(this.user);
        if (data == "error") return;
        this.$message.success("添加成功");
        this.initUserList();
        // console.log(1111, data);
      } catch (error) {
        console.log("UserView-addUserList-error:", error);
      }
    },
    //修改状态
    async updateUserSate(user) {
      try {
        let result = await this.$api.updateUserSateById(user.id, user.mg_state);
        // console.log(1111, result);
        if (result == "error") {
          user.mg_state = !user.mg_state;
        } else {
          this.$message.success("状态修改成功");
        }
      } catch (error) {
        console.log("UserView-updateUserSate-error:", error);
      }
      // console.log(22222, user);
    },
    //修改用户信息
    async modifyUserById() {
      let params = {
        email: this.user.email,
        mobile: this.user.mobile,
      };
      try {
        await this.$refs.updateUserForm.validate();
        // console.log(11222, this.user);
        let data = await this.$api.updateUserList(this.user.id, params);
        // console.log(12345, data);
        if (data == "error") return;
        this.$message.success("编辑成功");
        this.updateFormVisible = false;
        this.initUserList();
      } catch (error) {
        console.log("UserView-modifyUserById-error:", error);
      }
    },
    //删除用户
    async removeUserById(id) {
      try {
        let result = await this.$api.removeUserList(id);
        // console.log(22222, result);
        if (result == "error") return;
        this.$message.success("删除成功");

        //当删除的数据是最后一页的最后一条数据时，必须将pagenum-1，否则页面会显示pagenum的数据，处于无数据状态
        let lastFlag = this.total % this.pagesize == 1; //判断最后的页面是不是只有一条数据
        let lastPageFlag =
          Math.ceil(this.total / this.pagesize) == this.pagenum; //判断当前是否处于最后一页
        if (lastFlag && lastPageFlag && this.pagenum != 1) {
          this.pagenum = this.pagenum - 1;
        }

        //修改成功后数据刷新
        this.initUserList();
      } catch (error) {
        console.log("UserView-removeUserById-error:", error);
      }
      // console.log(11, id);
    },
    //拿到用户权限信息
    async allotLimit(row) {
      this.limitFormVisible = true;
      let roles = await this.$api.getRolesList();
      this.roles = roles;
      // console.log(111222,  this.roles);
      let params = {
        username: row.username,
        role_name: row.role_name,
      };
      this.id = row.id;
      // console.log(this.id);
      this.userlimit = params;
      // console.log(11, row);
    },
    //用户权限信息
    async updateLimitData() {
      try {
        await this.$refs.limitRoleForm.validate();
        await this.$api.allotUserRole(this.id, { rid: this.rid });
        // console.log('rid',this.rid,this.newRoleName, 'data', data);
        this.$message.success("权限修改成功");
        this.limitFormVisible = false;
        this.initUserList();
      } catch (error) {
        console.log("UserView-updateLimitData-error:", error);
      }
    },
    //pageSize改变时触发(每一页)
    reloadUserlistPage(newPageNum) {
      // console.log(this.pagenum, newPageNum);
      this.pagenum = newPageNum;
      this.initUserList();
    },
    //currentPage 改变时触发(当前页)
    reloadUserlistSize(newPagePage) {
      // console.log(this.pagenum,newPagePage);
      this.pagesize = newPagePage;
      this.initUserList();
    },
    //拿到当前点击的按钮的用户id
    updateUserData(user) {
      this.updateFormVisible = true;
      // console.log(2222, user);
      this.user = {
        id: user.id,
        username: user.username,
        password: user.password,
        email: user.email,
        mobile: user.mobile,
      };
    },
  },
  created() {
    //初始化数据请求
    this.initUserList();
  },
};
</script>
<style lang="less" scoped>
// .container {
//   width: 100%;
//   background-color: #fff;

// }
// .el-breadcrumb {
//   margin-bottom: 10px;
//   padding: 8px 0;
// }
// .el-pagination {
//   margin-top: 20px;
// }
.el-button,
.el-tooltip {
  margin: 0;
}
.addUser {
  margin-left: 22px;
}
.el-button,
.updateUser {
  margin-right: 10px;
}
.el-select {
  width: 100%;
}
</style>